﻿using Zero.WebAPI.Framework.DAL;
using Zero.WebAPI.Framework.Security.Model;
using Zero.WebAPI.Framework.Security.Models;

namespace Zero.WebAPI.Framework.Security
{
    public class PermissionService : IPermissionService
    {
        private IRepository repository;

        public PermissionService(IRepository repository)
        {
            this.repository = repository;
        }

        public bool CheckPermission(Identity identity, List<string> needPerms)
        {
            string principal = identity.ID;
            List<DataPermission> dataPermissions = repository.SqlQueryable<DataPermission>(
                $@"select dp.* from Data_User as du
                INNER JOIN Data_UserRole as ur on du.UID = ur.UserID 
                INNER JOIN Data_Role as r on ur.RoleID = r.RoleID 
                INNER JOIN Data_RolePermission as rp on rp.RoleID = r.RoleID 
                INNER JOIN Data_Permission as dp on rp.PermID = dp.PermID
                Where du.UID = {principal};").ToList();
            return needPerms.Any(perm => dataPermissions.Any(dp => dp.PermName == perm));
        }
    }
}
